import { Controller, Post, Query, Res, Headers, Logger } from '@nestjs/common';
import { Response } from 'express';
import { ReportsService } from './index.service';

// @todo 不要这个baseUrl
const baseUrlMap = {
  production: '/reports',
  test: '/reports-test',
  local: '/reports',
};

const route = `${baseUrlMap[process.env.ENV]}/print`;
Logger.log(`route: ${route}`);

@Controller(route)
export class ReportsController {
  private readonly logger = new Logger(ReportsController.name);

  constructor(private readonly reportsService: ReportsService) {}

  @Post()
  async printReport(
    @Query() query: any,
    @Headers() headers: any,
    @Res() res: Response,
  ) {
    try {
      // 打印当前 Node.js 版本
      this.logger.log(`当前 Node.js 版本: ${process.version}`);
      const pdfBuffer = await this.reportsService.generatePdf(query, headers);

      res.set({
        'Content-Type': 'application/pdf',
        'Content-Disposition': `attachment; filename=report-${Math.floor(Date.now() / 1000)}.pdf`,
      });

      res.status(200).send(Buffer.from(pdfBuffer));
      this.logger.log('PDF成功发送给客户端');
    } catch (error) {
      this.logger.error('处理请求时发生错误:', {
        message: error.message,
        stack: error.stack,
        query,
      });
      res.status(500).send('生成PDF时发生错误: ' + error.message);
    }
  }
}
